<template>
  <Drawer :title="title">
    <BaseForm>
      <template #classId="slotProps">
        <a-select
          class="w-2/5"
          v-bind="slotProps"
          :options="classOptions"
          mode="tags"
          :maxTagCount="3"
          @change="handleChange"
          placeholder="请选择图书分类"
        ></a-select>
      </template>
      <template #tagId="slotProps">
        <a-select
          class="w-2/5"
          v-bind="slotProps"
          :options="tagOptions"
          mode="tags"
          :maxTagCount="3"
          @change="handleTagChange"
          placeholder="请选择图书标签"
        ></a-select>
      </template>
    </BaseForm>
  </Drawer>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { querySave, queryUpdate } from '../data/api';
import {
  drawerFormSchema,
  handleId,
  idKey,
  classList,
  tagList,
} from '../data/options';
import { message } from 'ant-design-vue';
import { useThrottleFn } from '@vueuse/core';

const emit = defineEmits(['success']);
const title = computed(() => {
  return `${handleId.value ? '编辑' : '新增'}图书`;
});

// 分类选择数据
const classOptions = computed(() => {
  return classList.value.map((item) => {
    return {
      label: item.className,
      value: item.classId,
    };
  });
});

// 标签选择数据
const tagOptions = computed(() => {
  return tagList.value.map((item) => {
    return {
      label: item.tagName,
      value: item.tagId,
    };
  });
});

// 分类选择回调
const handleChange = (value: any) => {
  console.log('handleChange', value);
  if (value.length > 3) {
    message.warning('最多只能选择3个分类');
    formApi.setFieldValue('classId', value.slice(0, 3));
    return;
  }
};

// 标签选择回调
const handleTagChange = (value: any) => {
  console.log('handleTagChange', value);
  if (value.length > 3) {
    message.warning('最多只能选择3个标签');
    formApi.setFieldValue('tagId', value.slice(0, 3));
    return;
  }
};

// 抽屉提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  if (!values[idKey.value]) delete values[idKey.value];
  values.classId = values.classId.join(',');
  values.tagId = values.tagId.join(',');
  let query = values[idKey.value] ? queryUpdate : querySave;
  let res: any = await query({ ...values });
  message.success(res.message);
  onSucClose();
}, 1000);

// 抽屉配置
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/2',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => onConfirm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      let data = drawerApi.getData();
      data.classId = data?.classId.split(',');
      data.tagId = data?.tagId.split(',');
      handleId.value = data[idKey.value] || '';
      formApi.setValues({ ...data });
      // formApi.setFieldValue('classId', data?.classId.split(','));
      // formApi.setFieldValue('tagId', data?.tagId.split(','));
    }
  },
});

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});

const onSucClose = () => {
  drawerApi.close();
  emit('success');
};

// 提交按钮
const onConfirm = () => {
  formApi.submitForm();
};
</script>

<style lang="scss" scoped></style>
